<!--
 @description 帮助中心配置列表
 @fileName index.vue
 @author zengqiongying
 @created 2022/02/11 10:21:58
-->
<template>
  <div class="qup-full-page">
    <template v-if="showPageType==='floor'">
      <floor-page :page-show.sync="showPageType" :basic-data="activeRowData" edit-able />
    </template>
    <template v-if="showPageType==='detail'">
      <floor-page :page-show.sync="showPageType" :basic-data="activeRowData" />
    </template>
    <div v-show="!showPageType">
      <table-box
        ref="refTable"
        :selected-arry.sync="tableSelected"
        :table-config="tableConfig"
        :other-filters="otherFilters"
        :off-set="-10"
        table-row-key="id"
        show-index
        @btnOperate="btnOperate"
      />
      <basic-edit v-if="showEditBasic" ref="refBasicForm" :visible.sync="showEditBasic" :basic-data="activeRowData" @success="handleBasicSuccess" />
    </div>
  </div>
</template>

<script>
import { parseTime } from '@/utils'
import { queryBtnList } from '@/api/permissions'
import { deletePage, getPageDetail, updatePageSort, updatPageState } from './api/helpCenter'
import FloorPage from './floor/index'
import BasicEdit from './component/BasicEdit'
export default {
  name: 'HelpCenter',
  components: { BasicEdit, FloorPage },
  data() {
    const that = this
    return {
      showPageType: '', // 显示页面类型：floor 编辑楼层， detail详情
      showEditBasic: false, // 是否编辑基础信息
      activeRowData: '', // 当前选中行数据
      tableSelected: [], // 当前所选中表格行数据
      otherFilters: [], // 表格额外查询条件
      tableConfig: {
        interfacePath: `${process.env.VUE_APP_BASE_API}/api/v1/helpCenterPage/page`,
        hideFuncBar: false,
        pageSize: 20,
        sort: 'lastUpdateTime',
        setting: [
          {
            prop: 'pageName',
            label: '页面名称',
            minWidth: 130,
            className: 'btn-green',
            isButton: true,
            clickFun: this.handleToDetail
          },
          {
            prop: 'iconUrl',
            label: '页面图标',
            minWidth: 100,
            overflowHidden: false,
            sortable: false,
            type: 'hidden',
            align: 'center',
            render: (_h, row) => {
              const iconUrl = row.iconUrl || ''
              if (iconUrl) {
                const url = that.formatImageUrl(iconUrl)
                return (<div class='cate_img'><img src={url} /></div>)
              }
              return ''
            }
          },
          {
            prop: 'state',
            label: '状态',
            width: 100,
            type: 'select',
            propEnum: {
              domainCode: 'marketing',
              appCode: 'content-center',
              dictTypeCode: 'STATE'
            }
          },
          {
            prop: 'sort',
            label: '排序',
            minWidth: 200,
            sortable: false,
            type: 'hidden',
            overflowHidden: false,
            render: (_h, row) => {
              if (this.isProduction) {
                const btns = []
                if (this.hasPermission('top')) {
                  btns.push(<el-button type='text' size='mini' onClick={that.handleSort.bind(this, row, 3)} class='btn-green my-txt-btn'>置顶</el-button>)
                }
                if (this.hasPermission('up')) {
                  btns.push(<el-button type='text' size='mini' onClick={that.handleSort.bind(this, row, 1)} class='btn-green my-txt-btn'>上移</el-button>)
                }
                if (this.hasPermission('down')) {
                  btns.push(<el-button type='text' size='mini' onClick={that.handleSort.bind(this, row, 2)} class='btn-green my-txt-btn'>下移</el-button>)
                }
                if (this.hasPermission('bottom')) {
                  btns.push(<el-button type='text' size='mini' onClick={that.handleSort.bind(this, row, 4)} class='btn-green my-txt-btn'>置底</el-button>)
                }
                return _h('div', btns)
              } else {
                return (<div>
                  <el-button type='text' size='mini' onClick={that.handleSort.bind(this, row, 3)} class='btn-green my-txt-btn'>置顶</el-button>
                  <el-button type='text' size='mini' onClick={that.handleSort.bind(this, row, 1)} class='btn-green my-txt-btn'>上移</el-button>
                  <el-button type='text' size='mini' onClick={that.handleSort.bind(this, row, 2)} class='btn-green my-txt-btn'>下移</el-button>
                  <el-button type='text' size='mini' onClick={that.handleSort.bind(this, row, 4)} class='btn-green my-txt-btn'>置底</el-button>
                </div>)
              }
            }
          },
          {
            prop: 'createBy',
            label: '创建人',
            minWidth: 150,
            type: 'hidden'
          },
          {
            prop: 'createTime',
            label: '创建时间',
            minWidth: 150,
            type: 'hidden',
            formatData: ({ createTime }) => {
              return parseTime(createTime)
            }
          },
          {
            prop: 'lastUpdateBy',
            label: '修改人',
            minWidth: 150,
            type: 'hidden'
          },
          {
            prop: 'lastUpdateTime',
            label: '修改时间',
            minWidth: 150,
            type: 'hidden',
            formatData: ({ lastUpdateTime }) => {
              return parseTime(lastUpdateTime)
            }
          }],
        btnList: !this.isProduction ? [
          {
            buttonName: '新增',
            optCode: 'add',
            outerFlag: true
          },
          {
            buttonName: '编辑',
            optCode: 'edit',
            outerFlag: true
          },
          {
            buttonName: '配置楼层',
            optCode: 'configFloor',
            outerFlag: true
          },
          {
            buttonName: '删除',
            optCode: 'del',
            outerFlag: true
          },
          {
            buttonName: '启用',
            optCode: 'enable',
            outerFlag: true
          },
          {
            buttonName: '停用',
            optCode: 'disable',
            outerFlag: true
          }] : null
      },
      buttons: []
    }
  },
  watch: {
    showPageType(val, oldVal) {
      if (!val) {
        this.activeRowData = ''
      }
    }
  },
  created() {
    this.getBtnsList()
  },
  methods: {
    getBtnsList() {
      const menuCode = this.$route.query.menuCode
      if (!menuCode) return
      const buttonGroupCode = 'inRow'
      queryBtnList({ menuCode, buttonGroupCode }).then(res => {
        // res.data.groovyList
        this.buttons = (res.data && res.data.groovyList) || []
      })
    },
    hasPermission(code) {
      return this.buttons.filter(v => v.buttonCode === code).length > 0
    },
    btnOperate(code) {
      switch (code) {
        case 'add':
          this.handleEdit()
          break
        case 'edit':
          if (!this.singleJudge(this.tableSelected, '编辑', true)) {
            return
          }
          this.handleEdit(this.tableSelected[0])
          break
        case 'configFloor':
          if (!this.singleJudge(this.tableSelected, '配置楼层', true)) {
            return
          }
          this.handleConfigFloor(this.tableSelected[0])
          break
        case 'del':
          if (!this.singleJudge(this.tableSelected, '删除', true)) {
            return
          }
          this.handleDelete()
          break
        case 'disable':
          if (!this.singleJudge(this.tableSelected, '停用', true)) {
            return
          }
          this.handleChangeStatus(0) // state 1：启用  0：停用
          break
        case 'enable':
          if (!this.singleJudge(this.tableSelected, '启用', true)) {
            return
          }
          this.handleChangeStatus(1) // state 1：启用  0：停用
          break
        default:
          break
      }
    },
    // 刷新表格数据
    refreshTable(isInit) {
      this.$nextTick(() => {
        this.$refs.refTable.initTableData(isInit ? '' : 'onPage')
      })
    },
    // 详情跳转
    handleToDetail(row) {
      if (!row.id) {
        this.$message.warning('数据异常')
        return
      }
      if (this.loading) return
      this.loading = true
      getPageDetail(row.id).then(res => {
        this.loading = false
        if (res.data && res.data.id) {
          this.activeRowData = res.data
          this.$nextTick(() => {
            this.showPageType = 'detail'
          })
        } else {
          this.$message.warning('数据异常！无法查看详情')
        }
      }).catch(() => {
        this.loading = false
      })
    },
    // 配置楼层
    handleConfigFloor(row) {
      this.activeRowData = row
      this.$nextTick(() => {
        this.showPageType = 'floor'
      })
    },
    // 新增/编辑基础信息
    handleEdit(row) {
      this.activeRowData = row || ''
      this.$nextTick(() => {
        this.showEditBasic = true
      })
    },
    handleBasicSuccess(res) {
      const data = res.data
      const goConfig = res.goConfig // 是否前往配置
      this.refreshTable(!!data.id)
      if (goConfig) {
        this.showPageType = 'floor'
        this.activeRowData = data
        this.tableSelected = [data]
      }
    },
    /**
     * 处理启用/停用
     * @param {Number} state 1 启用 0 停用
     * @param {String} id
    */
    handleChangeStatus(state) {
      const tmpArr = this.tableSelected.filter(row => row.state === state)
      if (tmpArr.length > 0) {
        this.$message.warning(`当前所选内容包含${state ? '启用' : '停用'}状态，请勿重复操作`)
        return
      }
      this.$confirm(`此操作将当前所选内容${state ? '启用' : '停用'},是否继续`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const selectedIds = this.tableSelected.map(v => v.id)
        const params = { ids: selectedIds, state }
        updatPageState(params).then(res => {
          if (res.success === 1) {
            this.$message({
              message: res.msg || '操作成功',
              type: 'success'
            })
            this.refreshTable()
          }
        })
      })
    },
    // 删除处理
    handleDelete() {
      this.$confirm('此操作将永久删除该页面, 是否继续?', '删除提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const id = this.tableSelected[0].id
        deletePage(id).then(res => {
          if (res.success === 1) {
            this.$message({
              message: res.msg || '删除成功',
              type: 'success'
            })
            this.refreshTable()
          }
        })
      }).catch(() => {})
    },
    /**
     * 排序
     * @param {Object} row 排序行
     * @param {string} type 移动类型： 1 上移 ， 2 下移 ，3置顶， 4 置底
    */
    handleSort(row, type) {
      if (this.sorting) return
      const now = Date.now()
      if (this.sortTime) {
        const diffTime = Math.floor((now - this.sortTime) / 1000)
        // 对比排序操作时间差，大于2s的可操作
        if (diffTime < 2) return
      }
      this.sortTime = now
      const params = {
        id: row.id,
        type
      }
      this.sorting = true
      updatePageSort(params).then(res => {
        this.sorting = false
        if (res.success === 1) {
          this.refreshTable()
        }
      }).catch(() => {
        this.sorting = false
      })
    }
  }
}
</script>
<style lang='scss' scoped>

  .my-txt-btn{
    padding: 0 !important;
  }
 .cate_img{
    padding: 5px 0;
    line-height: 0;
    font-size: 0;
    img{
      width: 70px;
      height: 70px;
      // object-fit: cover;
      object-fit: contain;
    }
  }
</style>
